<?php

declare (strict_types = 1);

namespace auth\middleware;

use auth\contract\Factory as Auth;

/**
 * 用户认证中间件
 */
class Authenticate
{
    /**
     * @var \auth\contract\Factory
     */
    protected $auth;

    /**
     * 实例化中间件
     *
     * @param  \auth\contract\Factory  $auth
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    public function handle($request, \Closure $next, $guard = null)
    {
        if (!$this->auth->guard($guard)->check()) { /* 未通过认证 */
            return unexpected_response(
                ERROR_CODE_UNAUTHORIZED,
                'Unauthorized.',
                401
            );
        }

        return $next($request);
    }
}
